/*
 * For legal stuff see the file COPYRIGHT
 */
#import "ExpenseEditor.h"
#import "Controller.h"

@implementation ExpenseEditor

- awakeFromNib
{
  [descriptionField setScrollable:YES];
  return self;
}

/*
 * Allow only one ExpenseEditor object to be created.
 */
+ new
{
  static id editor;

  if ( ! editor ) {
    editor = [[ExpenseEditor alloc] init];
    [NXApp loadNibSection:"ExpenseEditor.nib" owner:editor withNames:NO];
  }

  return editor;
}

- init
{
  [super init];
  return self;
}

- free
{
  return [super free];
}

- (float)amount
{
  return [amountField floatValue];
}

- (const char *)dateString
{
  return [dateField stringValue];
}

- (const char *)description
{
  return [descriptionField stringValue];
}

- (void)clearFields
{
  [dateField        setStringValue:""];
  [descriptionField setStringValue:""];
  [amountField      setStringValue:""];
}

/*
 * Display the contents of an expense object
 */
- (void)loadExpense:(Expense *)expense
{
  if ( expense == nil ) {
    [self clearFields];
    [dateField setStringValue:currentDate()];
  } else {
    [dateField        setStringValue:[expense dateString]];
    [descriptionField setStringValue:[expense description]];
    [amountField      setFloatValue: [expense amount]];
  }
}

/*
 * Copy the data from the form into the expense object. If the
 * object is nil, allocate one and return it.
 */
- (Expense *)saveExpense:(Expense *)expense
{
  if ( expense == nil )
    expense = [[Expense alloc] init];
  
  [expense setDateString: [dateField stringValue]];
  [expense setDescription:[descriptionField stringValue]];
  [expense setAmount:     [amountField floatValue]];

  return expense;
}

/*
 * This routine should check that there is enough data to be useful...
 */
- (Expense *)editItem:(Expense *)expense
{
  int value ;

  [self loadExpense:expense];
  [form selectTextAt:0];	/* always select the first field */

  value = [NXApp runModalFor:panel] ;
  [panel close];

  switch ( value  ) {
  case NX_RUNSTOPPED:
    return [self saveExpense:expense];	/* copy data back into struct */

  default:
  case NX_RUNABORTED:
    return nil;
  }
}

- cancel:sender
{
  [NXApp abortModal];
  return self;
}

- ok:sender
{
  int dummy;

  /* This is pretty cheesey. */
  if ( sscanf( [dateField stringValue], "%d/%d/%d",
	      &dummy, &dummy, &dummy ) != 3 ) {
    NXRunAlertPanel( [NXApp name], "Valid date (mm/dd/yy) required.",
		    "Pardon me", NULL, NULL );
  } else
    [NXApp stopModal];

  return self;
}

@end


